package logic

import (
	"context"
	"strconv"

	"github.com/iriver/ai-offer/backend/internal/model"
	"github.com/iriver/ai-offer/backend/internal/svc"
	"github.com/iriver/ai-offer/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type GetUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLogic {
	return &GetUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserLogic) GetUser(userId string) (resp *types.UserResponse, err error) {
	// 将用户ID字符串转换为int64
	id, err := strconv.ParseInt(userId, 10, 64)
	if err != nil {
		l.Logger.Errorf("无效的用户ID: %s, %v", userId, err)
		return nil, httpx.NewCodeError(types.ErrInvalidParams, "无效的用户ID")
	}

	// 查询用户
	user, err := l.svcCtx.UserStore.FindOne(id)
	if err != nil {
		if err == model.ErrNotFound {
			l.Logger.Infof("用户不存在: %d", id)
			return nil, httpx.NewCodeError(types.ErrUserNotFound, "用户不存在")
		}
		l.Logger.Errorf("查询用户失败: %v", err)
		return nil, httpx.NewCodeError(types.ErrDatabase, "获取用户信息失败，请稍后重试")
	}

	// 构建响应
	resp = &types.UserResponse{
		Id:        user.ID,
		Email:     user.Email,
		Name:      user.Name,
		AvatarUrl: user.AvatarUrl,
		Role:      user.Role,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return resp, nil
}
